import { FC, useEffect, useRef, useState } from "react";
import APlayer from "aplayer";
import { get } from "lodash";

const AudioCore: FC<{
  name: string;
  posterUrl: string;
  source: string;
  pointList?: [number, number][];
}> = ({ source, pointList, name, posterUrl }) => {
  const [duration, setDuration] = useState(0);
  const elRef = useRef();
  const [player, setPlayer] = useState<any>(null);
  useEffect(() => {
    if (!elRef.current) return;
    const ap = new APlayer({
      container: elRef.current,
      audio: [
        {
          name,
          artist: "",
          url: source,
          cover: posterUrl,
        },
      ],
    });
    ap.on("durationchange", () => {
      setDuration(ap.audio.duration);
    });
    ap.on('canplay', () => {
      setPlayer(ap);
    })
  }, [source, name, posterUrl]);

  useEffect(() => {
    if (!player) return;
    // if (player && prevPointListRef.current && prevPointListRef.current !== pointList) {
    const hopeTime = get(pointList, "[0][0]", 0);
    player?.seek?.(hopeTime);
    // }
    // prevPointListRef.current = pointList;
  }, [player, pointList]);

  useEffect(() => {
    return () => {
      if (!player) return;
      player.destroy();
    }
  }, [player])

  useEffect(() => {
    if (!elRef.current) return;
    setTimeout(() => {
      const playerBarEl = elRef.current.querySelector(".aplayer-bar");
      if (!playerBarEl) return;
      let pointerEl = playerBarEl.querySelector(".aplayer-pointer-wrapper");
      if (!pointerEl) {
        pointerEl = document.createElement("div");
        pointerEl.classList.add("aplayer-pointer-wrapper");
        playerBarEl.append(pointerEl);
      }
      pointerEl.innerHTML = "";
      const virtualEl = document.createDocumentFragment();
      pointList.forEach(([start, end]) => {
        const width = ((end - start) / duration) * 100 + "%";
        const left = (start / duration) * 100 + "%";
        const el = document.createElement("div");
        el.style.width = width;
        el.style.left = left;
        el.classList.add("aplayer-pointer-item");
        virtualEl.append(el);
      });
      pointerEl.append(virtualEl);
    }, 500);
  }, [pointList, duration]);
  return <div ref={elRef} />;
};

export default AudioCore;
